/* hooks */
import { useFetchSettingGPTRobotApp, useInitXiaoBaoChat, useSettingGPTRobotAppEditStatus } from '@gpt/hooks';
import { useLoading } from '@hooks/useLoading';
import { onMounted } from 'vue';
/* api */
import { updateRobotApp } from '@src/api/AIApi';
/* types */
import { SettingGPTPromptWordItem } from '@gpt/types';
import MsgModel from '@model/MsgModel';
/* util */
import { message } from '@src/util/message';

/**
 * @description 获取用户机器人数据
 */
function useGetFetchUserData() {
  
  const { fetchGptRobotApp, gptRobotApp, loading } = useFetchSettingGPTRobotApp();
  const { robotId, robotAppId } = useSettingGPTRobotAppEditStatus();
  
  onMounted(() => {
    fetchGptRobotApp({
      robotId: robotId.value,
      id: robotAppId.value,
    });
  });
  
  return {
    loading,
    fetchGptRobotApp,
    gptRobotApp,
  };
}

/**
 * @description 保存提示词信息
 */
function useSaveGptRobotApp() {
  
  const { loading, setLoading, clearLoading } = useLoading();
  const { robotId, robotAppId } = useSettingGPTRobotAppEditStatus();
  
  const {
    initChat
  } = useInitXiaoBaoChat()
  
  const saveFetchApp = (params: SettingGPTPromptWordItem[]) => {
    setLoading();
    return updateRobotApp({
      promptWordList: params,
      robotId: robotId.value,
      robotAppId: robotAppId.value,
    })
    .then((result) => {
      
      const isSuccess = MsgModel.isSuccess(result);
      
      if (isSuccess) {
        initChat();
        message.success('保存成功');
      } else {
        message.error(MsgModel.getMessage(result))
      }
      
    })
    .finally(() => {
      clearLoading();
    });
  };
  
  return {
    loading,
    saveFetchApp,
  };
}

export { useGetFetchUserData, useSaveGptRobotApp };
